const BaseComponent = require('../../prototype/baseComponent');
const resourcesModel = require('../../models/resources/index');

class Resources extends BaseComponent {
  constructor() {
    super()
  }
  getAll = async (req, res, next) => {
    try {
      let { page = 1, limit = 10 } = req.query
      let list = await resourcesModel.find({}, { '__v': 0 }, { lean: true }).populate('category_id').skip(Number((page - 1) * limit)).limit(Number(limit))
      let total = await resourcesModel.estimatedDocumentCount()
      let body = {
        code: 0,
        data: {
          list: list,
          total: total
        },
        message: '查询成功'
      }
      res.send(body);
    } catch (err) {
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  save = async (req, res, next) => {
    try {
      let { img_url = '', category_id = '' } = req.body
      let item = {
        _id: this.createId(),
        img_url: img_url,
        category_id: category_id
      }
      await resourcesModel.create(item)
      let body = {
        code: 0,
        message: '新增成功'
      }
      res.send(body)
    } catch (err) {
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  del = async (req, res, next) => {
    try {
      let { _id = '' } = req.body
      if (!_id) throw new Error("请填写id")
      let details = await resourcesModel.findOneAndRemove({ _id: _id })
      if (!details) throw new Error("没有此项，请检查id是否正确")
      let body = {
        code: 0,
        message: '删除成功'
      }
      res.send(body);
    } catch (err) {
      this.error(`删除失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
}
module.exports = new Resources()